﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace SharpSoft.WPF.Validations
{
    /// <summary>
    /// 数字验证规则
    /// </summary>
    public class NumericValidationRule : ValueValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var vr = base.Validate(value, cultureInfo);
            if (vr != Uncertainty)
            {
                return vr;
            }
            var str = value.ToString();
            if (value is IConvertible cov)
            {
                str = cov.ToDouble(null).ToString();
            }
            if (value.GetType().IsEnum)
            {
                str = Convert.ToDouble(value).ToString();
            }

            if (!double.TryParse(str, out double d))
            {
                return new ValidationResult(false, NotNumericError);
            }
            if (!AllowFloat && str.Contains('.'))
            {
                return new ValidationResult(false, FloatError);
            }
            if (MinValue.HasValue && d < MinValue.Value)
            {
                return new ValidationResult(false, string.Format(LessThanMinValueError, MinValue));
            }
            if (MaxValue.HasValue && d > MaxValue.Value)
            {
                return new ValidationResult(false, string.Format(GreaterThanMaxValueError, MaxValue));
            }
            return ValidationResult.ValidResult;
        }
        /// <summary>
        /// 当值不是有效的数值对象时的错误消息
        /// </summary>
        public string NotNumericError { get; set; } = "不是有效的数值";
        /// <summary>
        /// 最小值
        /// </summary>
        public double? MinValue { get; set; }
        /// <summary>
        /// 小于最小值时的错误消息
        /// </summary>
        public string LessThanMinValueError { get; set; } = "不能小于{0}";
        /// <summary>
        /// 最大值
        /// </summary>
        public double? MaxValue { get; set; }
        /// <summary>
        /// 大于最大值时的错误消息
        /// </summary>
        public string GreaterThanMaxValueError { get; set; } = "不能大于{0}";
        /// <summary>
        /// 是否允许小数
        /// </summary>
        public bool AllowFloat { get; set; }
        /// <summary>
        /// 当出现小数时的错误消息
        /// </summary>
        public string FloatError { get; set; } = "不允许输入小数";


    }
}
